package com.baoyouqun.controller.weixin;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.cola.dto.Response;
import com.alibaba.cola.dto.SingleResponse;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baoyouqun.base.PageResponse;
import com.baoyouqun.domain.CreateCmd.DemandCmd;
import com.baoyouqun.domain.CreateCmd.DemandCreateCmd;
import com.baoyouqun.domain.Query.DemandQuery;
import com.baoyouqun.domain.Query.DemandUserQuery;
import com.baoyouqun.domain.UpdateCmd.DemandUpdateCmd;
import com.baoyouqun.domain.VO.DemandVO;
import com.baoyouqun.domain.VO.PostTypeDTO;
import com.baoyouqun.service.DemandService;
import com.baoyouqun.service.SystemConfigService;
import com.baoyouqun.service.UserFollowPostTypeService;
import com.baoyouqun.service.UserVipTimeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/wx/demand")
@Api(tags = "需求发布表管理接口")
public class WxDemandController {

    @Resource
    private DemandService demandService;
    @Resource
    private SystemConfigService systemConfigService;
    @Resource
    private UserVipTimeService userVipTimeService;
    @Resource
    private UserFollowPostTypeService userFollowPostTypeService;

    @PostMapping("create")
    @ApiOperation("新增需求发布表")
    public SingleResponse<DemandVO> create(@Valid @RequestBody DemandCreateCmd cmd) {
        String userId = StpUtil.getLoginIdAsString();
        cmd.setUserId(userId);
        if (!userVipTimeService.checkByUserId(userId)) {
            return SingleResponse.buildFailure("100777", "非VIP用户无权限");
        }
        return demandService.create(cmd);
    }

    @PutMapping("update")
    @ApiOperation("修改需求发布表")
    public Response update(@Valid @RequestBody DemandUpdateCmd cmd) {
        return demandService.update(cmd);
    }

    @DeleteMapping("delete")
    @ApiOperation("根据ID删除需求发布表")
    public Response delete(String id) {
        DemandVO demandVO = demandService.selectById(id);
        if (Objects.isNull(demandVO)) {
            return Response.buildFailure("100301", "记录不存在");
        }
        String userId = StpUtil.getLoginIdAsString();
        if (!Objects.equals(demandVO.getUserId(), (userId))) {
            return Response.buildFailure("100302", "无权限操作删除");
        }
        demandService.removeById(id);
        return Response.buildSuccess();
    }

    @GetMapping("getById")
    @ApiOperation("根据ID查询需求详情")
    public SingleResponse<DemandVO> selectById(String id) {
        String userId = StpUtil.getLoginIdAsString();
        if (!userVipTimeService.checkByUserId(userId)) {
            return SingleResponse.buildFailure("100777", "非VIP用户无权限查看");
        }

        return SingleResponse.of(demandService.selectById(id));
    }

    @SaIgnore
    @ApiOperation("帖子类型配置获取（按用户关注优先排序）")
    @GetMapping("/post-type")
    public SingleResponse<PostTypeDTO> getPostType() {
        // 1. 获取原始帖子类型数据
        PostTypeDTO postTypeDTO = systemConfigService.getPostType();
        if (postTypeDTO == null || postTypeDTO.getList() == null) {
            return SingleResponse.of(postTypeDTO);
        }

        // 2. 获取用户关注的类型标题（仅登录用户）
        List<String> followTitles = new ArrayList<>();
        if (StpUtil.isLogin()) {
            String userId = StpUtil.getLoginIdAsString();
            List<PostTypeDTO.PostTypeSonDTO> followTypes = userFollowPostTypeService.getUserFollowPostTypes(userId);
            // 提取关注的类型标题
            followTitles = followTypes.stream()
                    .map(PostTypeDTO.PostTypeSonDTO::getTitle)
                    .toList();
        }

        // 3. 对原始类型列表排序：已关注的排在前面，未关注的排在后面
        List<String> finalFollowTitles = followTitles;
        List<PostTypeDTO.PostTypeSonDTO> sortedSonList = postTypeDTO.getList().stream()
                .sorted((a, b) -> {
                    boolean aIsFollow = finalFollowTitles.contains(a.getTitle());
                    boolean bIsFollow = finalFollowTitles.contains(b.getTitle());
                    if (aIsFollow && !bIsFollow) {
                        return -1; // a在前
                    } else if (!aIsFollow && bIsFollow) {
                        return 1; // b在前
                    } else {
                        return 0; // 同状态保持原有顺序
                    }
                })
                .toList();

        // 4. 设置排序后的列表并返回
        postTypeDTO.setList(sortedSonList);
        return SingleResponse.of(postTypeDTO);
    }

    @SaIgnore
    @GetMapping("wxHomePage")
    @ApiOperation("需求广场分页")
    public PageResponse<DemandVO> page(DemandQuery query) {
        if (!StpUtil.isLogin()) {
            if (query.getCurrent() > 1) {
                return PageResponse.of(new ArrayList<>(), 10, query.getCurrent(), query.getSize());
            }
        }

        IPage<DemandVO> page = demandService.wxHomePage(query);
        return PageResponse.of(page.getRecords(), page.getTotal(), page.getCurrent(), page.getSize());
    }

    @GetMapping("userPage")
    @ApiOperation("我发布的需求列表")
    public PageResponse<DemandVO> userPage(DemandUserQuery query) {
        String userId = StpUtil.getLoginIdAsString();
        query.setUserId(userId);
        IPage<DemandVO> page = demandService.userPageVo(query);
        return PageResponse.of(page.getRecords(), page.getTotal(), page.getCurrent(), page.getSize());
    }


    @GetMapping("userCollectionPage")
    @ApiOperation("我收藏列表")
    public PageResponse<DemandVO> userCollectionPage(DemandUserQuery query) {
        String userId = StpUtil.getLoginIdAsString();
        query.setUserId(userId);
        IPage<DemandVO> page = demandService.userCollectionPage(query);
        return PageResponse.of(page.getRecords(), page.getTotal(), page.getCurrent(), page.getSize());
    }

    @PutMapping("refreshTop")
    @ApiOperation("刷新置顶需求")
    public Response refreshTop(@Valid @RequestBody DemandCmd cmd) {
        // 校验用户权限，假设需求发布者才有置顶权限
        String userId = StpUtil.getLoginIdAsString();
        if (!userVipTimeService.checkByUserId(userId)) {
            return SingleResponse.buildFailure("100777", "非VIP用户无权限操作");
        }
        // 这里需要根据需求ID查询需求发布者ID并对比，假设DemandService有此方法
        boolean hasPermission = demandService.checkUserPermission(cmd.getDemandId(), userId);
        if (!hasPermission) {
            return Response.buildFailure("100302", "无权限操作");
        }
        return demandService.refreshTop(cmd.getDemandId());
    }


    @PutMapping("takeOffShelves")
    @ApiOperation("下架需求")
    public Response takeOffShelves(@Valid @RequestBody DemandCmd cmd) {
        String demandId = cmd.getDemandId();

        // 校验用户权限，假设需求发布者才有下架权限
        String userId = StpUtil.getLoginIdAsString();
        // 这里需要根据需求ID查询需求发布者ID并对比，假设DemandService有此方法
        boolean hasPermission = demandService.checkUserPermission(demandId, userId);
        if (!hasPermission) {
            return Response.buildFailure("100302", "无权限操作");
        }
        return demandService.takeOffShelves(demandId);
    }

}